package com.buddy.learn.javasource._thread;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author Buddy
 * @date 2021/4/18
 */
public class PrintABCUseCondition {

    private int times;
    private int state;
    private Lock lock = new ReentrantLock();
    private Condition conditionA = lock.newCondition();
    private Condition conditionB = lock.newCondition();
    private Condition conditionC = lock.newCondition();

    public PrintABCUseCondition(int times) {
        this.times = times;
    }

    public void printA(){
        print("A",0,conditionA,conditionB);
    }

    public void printB(){
        print("B",1,conditionB,conditionC);
    }

    public void printC(){
        print("C",2,conditionC,conditionA);
    }

    private void print(String value, int targetState, Condition current, Condition next) {
        for (int i=0;i<times;){
            lock.lock();
            try{
                while (state % 3 != targetState){
                    current.await();
                }
                state++;
                i++;
                System.out.println(i+":"+value);
                next.signal();
            }catch (Exception e){
                e.printStackTrace();
            }finally {
                lock.unlock();
            }
        }
    }


}
